<template>
  <a-card :bordered="false">
    <div class="table-page-search-wrapper">
    </div>
    <div class="table-operator">
      <a-button type="primary" icon="plus" @click="handleAdd">新建</a-button>
      <a-dropdown v-action:edit v-if="selectedRowKeys.length > 0">
        <a-menu slot="overlay">
          <a-menu-item key="1"><a-icon type="delete" />删除</a-menu-item>
          <!-- lock | unlock -->
          <a-menu-item key="2"><a-icon type="lock" />锁定</a-menu-item>
        </a-menu>
        <a-button style="margin-left: 8px">
          批量操作 <a-icon type="down" />
        </a-button>
      </a-dropdown>
    </div>
    <a-table
      ref="table"
      size="default"
      rowKey="id"
      @expand="expand"
      :expandedRowKeys="expandedRowKeys"
      :columns="columns"
      :data-source="categoryList"
      :pagination="false"
    >
      <span slot="iconUrl" slot-scope="text">
        <img v-if="text" :src="text" class="list_icon" />
      </span>
      <span slot="picUrl" slot-scope="text">
        <img v-if="text" :src="text" class="list_pic" />
      </span>
      <span slot="catLevel" slot-scope="text">
        <a-tag v-if="text === 'L1'" color="green">
          一级类目
        </a-tag>
        <a-tag v-else>
          二级类目
        </a-tag>
      </span>
      <template slot="operation" slot-scope="text, record">
        <div class="editable-row-operations">
          <a @click="() => editCategory(record)">编辑</a>
          <a-divider type="vertical" />
          <a-popconfirm title="确定要删除?" @confirm="() => deleteCategory(record.id)">
            <a>删除</a>
          </a-popconfirm>
        </div>
      </template>
    </a-table>
    <a-modal v-model="modalVisible" :title="modalTitle" width="800px">
      <a-form :form="catForm" :label-col="{ span: 5 }" :wrapper-col="{ span: 12 }">
        <a-form-item label="类目ID" style="display: none">
          <a-input
            v-decorator="['id']"
          />
        </a-form-item>
        <a-form-item label="类目名称">
          <a-input
            v-decorator="['name', { rules: [{ required: true, message: '请输入类目名称!' }] }]"
          />
        </a-form-item>
        <a-form-item label="关键字">
          <a-input
            v-decorator="['keywords']"
          />
        </a-form-item>
        <a-form-item label="类目级别">
          <a-select
            v-decorator="['catLevel', { initialValue: 'L1' }]"
            @change="handleCatLevelChange"
          >
            <a-select-option value="L1"> 一级类目 </a-select-option>
            <a-select-option value="L2"> 二级类目 </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="父级类目" v-if="catLevel == 'L2'">
          <a-select
            v-decorator="['pid', { initialValue: 0 }]"
          >
            <a-select-option v-for="item in mainCatList" :key="item.id" :value="item.id"> {{ item.name }} </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="排序">
          <a-input-number v-decorator="['sortOrder']" :min="0" :max="100" />
        </a-form-item>
        <a-form-item label="类目图标">
          <a-upload
            v-decorator="[
              'iconFile', {getValueFromEvent: normFile}
            ]"
            name="file"
            list-type="picture-card"
            class="avatar-uploader"
            :show-upload-list="false"
            :action="uploadPath"
            :before-upload="beforeUpload"
            @change="handleIconUploadChange"
          >
            <img class="icon_img" v-if="iconUrl" :src="iconUrl" alt="avatar" />
            <div v-else>
              <a-icon :type="uploadLoading ? 'loading' : 'plus'" />
              <div class="ant-upload-text">
                上传图标
              </div>
            </div>
          </a-upload>
        </a-form-item>
        <a-form-item label="类目图片">
          <a-upload
            v-decorator="[
              'pictureFile',
              {
                getValueFromEvent: normFile,
              }
            ]"
            name="file"
            list-type="picture-card"
            class="avatar-uploader"
            :show-upload-list="false"
            :action="uploadPath"
            :before-upload="beforeUpload"
            @change="handlePicUploadChange"
          >
            <img class="icon_img" v-if="picUrl" :src="picUrl" alt="avatar" />
            <div v-else>
              <a-icon :type="uploadPicLoading ? 'loading' : 'plus'" />
              <div class="ant-upload-text">
                上传图标
              </div>
            </div>
          </a-upload>
        </a-form-item>
        <a-form-item label="类目介绍">
          <a-input
            v-decorator="['catDesc']"
          />
        </a-form-item>
      </a-form>
      <template slot="footer">
        <a-button @click="modalVisible = false">取消</a-button>
        <a-button v-if="dialogStatus=='create'" :loading="loading" type="primary" @click="createCategory">确定</a-button>
        <a-button v-else type="primary" :loading="loading" @click="updateCategory">更新</a-button>
      </template>
    </a-modal>
  </a-card>
</template>

<script>
import { getToken } from '@/utils/util'
import { getCategoryList, getMainCatList, createCategory, updateCategory, deleteCategory } from '@/api/goods'
import { uploadPath } from '@/api/storage'

const columns = [
  {
    title: '类目ID',
    dataIndex: 'id'
  },
  {
    title: '类目名称',
    dataIndex: 'name'
  },
  {
    title: '类目图标',
    dataIndex: 'iconUrl',
    scopedSlots: { customRender: 'iconUrl' }
  },
  {
    title: '类目图片',
    dataIndex: 'picUrl',
    scopedSlots: { customRender: 'picUrl' }
  },
  {
    title: '关键字',
    dataIndex: 'keywords'
  },
  {
    title: '介绍',
    dataIndex: 'catDesc'
  },
  {
    title: '级别',
    dataIndex: 'catLevel',
    scopedSlots: { customRender: 'catLevel' }
  },
  {
    title: '操作',
    dataIndex: 'operation',
    scopedSlots: { customRender: 'operation' }
  }
]

export default {
  name: 'CategoryList',
  components: { },
  data () {
    this.columns = columns
    return {
      catLevel: 'L1',
      expandedRowKeys: [],
      iconUrl: '',
      picUrl: '',
      uploadPath,
      modalTitle: '创建分类',
      labelCol: { span: 4 },
      wrapperCol: { span: 14 },
      // create model
      modalVisible: false,
      confirmLoading: false,
      mdl: null,
      // 高级搜索 展开/关闭
      advanced: false,
      categoryList: [],
      mainCatList: [], // 添加类目的时候使用
      // 查询参数
      queryParam: {},
      selectedRowKeys: [],
      selectedRows: [],
      catForm: this.$form.createForm(this, { name: 'catForm' }),
      uploadLoading: false,
      uploadPicLoading: false,
      loading: false,
      dialogStatus: 'create'
    }
  },
  created () {
    console.log(uploadPath)
    // 获取商品类目
    this.initCategoryList()
  },
  computed: {
    headers () {
      return {
        'X-Ayouth-Shop-Admin-Token': getToken()
      }
    }
  },
  methods: {
    expand (expanded, record) {
      this.isExpend = expanded
      this.expandedRowKeys = [] // 重置展开节点，只展开当前点击的节点（内部数据调用模板，无法做到同时几个内层表格数据直接缓存在页面）
      if (expanded) {
        this.expandedRowKeys = [record.id]
      }
    },
    handleIconUploadChange (info) {
      if (info.file.status === 'uploading') {
        this.uploadLoading = true
        return
      }
      if (info.file.status === 'done') {
        this.iconUrl = info.file.response.data.storageInfo.fileUrl
        this.uploadLoading = false
      }
    },
    handlePicUploadChange (info) {
      if (info.file.status === 'uploading') {
        this.uploadPicLoading = true
        return
      }
      if (info.file.status === 'done') {
        this.picUrl = info.file.response.data.storageInfo.fileUrl
        this.uploadPicLoading = false
      }
    },
    normFile (e) {
      if (Array.isArray(e)) {
        return e[0]
      }
      return e && e.file
    },
    editCategory (record) {
      console.log(record)
      // 显示Modal
      this.catLevel = record.catLevel
      this.dialogStatus = 'update'
      this.modalTitle = '编辑分类'
      this.modalVisible = true
      this.$nextTick(() => {
        this.iconUrl = record.iconUrl
        this.picUrl = record.picUrl
        // 设置页面显示的属性
        this.catForm.setFieldsValue({
          id: record.id,
          name: record.name,
          catLevel: record.catLevel,
          keywords: record.keywords,
          catDesc: record.catDesc,
          sortOrder: record.sortOrder
        })
        if (this.catLevel === 'L2') {
          this.catForm.setFieldsValue({
            pid: record.pid
          })
        }
      })
    },
    deleteCategory (id) {
      // 删除数据
      deleteCategory({ id: id }).then(res => {
        // 刷新列表
        this.initCategoryList()
      })
    },
    createCategory (e) {
      e.preventDefault()
      const me = this
      this.catForm.validateFields((err, values) => {
        if (!err) {
          // 判断一级二级分类
          if ((values.catLevel === 'L2') && (values.pid <= 0)) {
            me.$message.error('请选择父级类目')
            return false
          }
          // 设置图片
          if (values.iconFile) {
            values.iconUrl = me.iconUrl
          }
          if (values.pictureFile) {
            values.picUrl = me.picUrl
          }
          // 开始保存信息
          me.loading = true
          console.log('Received values of form: ', values)
          createCategory(values).then(res => {
            me.loading = false
            console.log(res)
            // 隐藏modal
            me.modalVisible = false
            // 刷新列表
            me.initCategoryList()
          })
        }
      })
    },
    updateCategory () {
      const me = this
      this.catForm.validateFields((err, values) => {
        if (!err) {
          if (values.id <= 0) {
            me.$message.error('参数错误：该类目ID不存在。')
            return false
          }
          // 判断一级二级分类
          if ((values.catLevel === 'L2') && (values.pid <= 0)) {
            me.$message.error('请选择父级类目')
            return false
          }
          // 设置图片
          if (values.iconFile) {
            values.iconUrl = me.iconUrl
          }
          if (values.pictureFile) {
            values.picUrl = me.picUrl
          }
          // 开始保存信息
          me.loading = true
          console.log('Received values of form: ', values)
          updateCategory(values).then(res => {
            me.loading = false
            console.log(res)
            // 隐藏modal
            me.modalVisible = false
            // 刷新列表
            me.initCategoryList()
          })
        }
      })
    },
    beforeUpload (file) {
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
      if (!isJpgOrPng) {
        this.$message.error('请选择JPG或PNG格式文件!')
      }
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isLt2M) {
        this.$message.error('图片必须小于 2MB!')
      }
      return isJpgOrPng && isLt2M
    },
    handleCatLevelChange (value) {
      console.log(value)
      if (value === 'L1') {
        this.catLevel = 'L1'
        this.catForm.setFieldsValue({
          pid: 0
        })
      } else {
        this.catLevel = 'L2'
      }
    },
    // 初期函数
    initCategoryList () {
      getCategoryList(this.queryParam).then(res => {
        this.categoryList = res.data.categoryList
      })
      getMainCatList().then(res => {
        this.mainCatList = res.data.catList
      })
    },
    handleAdd () {
      this.initForm()
      this.modalTitle = '创建分类'
      this.dialogStatus = 'create'
      this.modalVisible = true
    },
    initForm () {
      this.iconUrl = ''
      this.picUrl = ''
      this.catForm.resetFields()
    }
  }
}
</script>

<style lang="less" scoped>
.icon_img {
  width: 102px;
  height: 102px;
}
.list_icon {
  width: 40px;
  height: 40px;
}
.list_pic {
  width: 80px;
  height: 30px;
}
</style>
